<template>
  <el-dialog
    width="30%"
    :visible="visible"
    :title="title"
    class="add-user-dialog"
    align-center
    @opened="handleDialogOpen"
    @close="closeDialog"
  >
    <el-form
      :model="userForm"
      :rules="userRules"
      ref="userFormRef"
      label-width="120px"
    >
      <el-form-item label="用户名" prop="loginName">
        <el-input v-model="userForm.loginName" />
      </el-form-item>
      <el-form-item label="真实姓名" prop="userName">
        <el-input v-model="userForm.userName" />
      </el-form-item>
      <el-form-item label="联系电话" prop="userPhone">
        <el-input v-model="userForm.userPhone" />
      </el-form-item>
      <el-form-item v-if="!userForm.pkid" label="密码" prop="loginPassword">
        <el-input
          v-model="userForm.loginPassword"
          type="password"
          show-password
          autocomplete="new-password"
        />
      </el-form-item>
      <el-form-item
        v-if="!userForm.pkid"
        label="确认密码"
        prop="confirmPassword"
      >
        <el-input
          v-model="userForm.confirmPassword"
          type="password"
          show-password
          autocomplete="new-password"
        />
      </el-form-item>
      <el-form-item label="用户角色" prop="roleId">
        <el-select v-model="userForm.roleId" placeholder="请选择" clearable>
          <el-option
            v-for="(item, index) in userRoleDict"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="用户所属区域" prop="refId">
        <el-cascader
          :options="areaList"
          v-model="pkids"
          @change="handleAreaCodeChange"
          :props="cascaderProps"
          clearable
          placeholder="请选择"
          :show-all-levels="false"
        />
      </el-form-item>
      <!--      <el-form-item label="备注" prop="remark">-->
      <!--        <el-input-->
      <!--          v-model="userForm.remark"-->
      <!--          type="textarea"-->
      <!--          :autosize="{ minRows: 6, maxRows: 6 }"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item label="状态">
        <el-radio-group v-model="userForm.userState">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="2">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="onSubmit"> 确定 </el-button>
        <el-button @click="closeDialog">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import type { PropType } from 'vue'
import { addUser, updateUser } from '@/api/back-management/user'
import type { updateUserParams } from '@/api/back-management/user/interface'
import { queryDeptListOld } from '@/api/back-management/dept'
import type { DivisionData, OptionData, ValidatorCallback } from '@/utils/type'
import { Message } from 'element-ui'
import { Base64 } from 'js-base64'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  userInfo: {
    type: Object,
    default: () => {},
  },
  userRoleDict: {
    type: Array as PropType<OptionData[]>,
    default: () => [],
  },
})

const cascaderProps = {
  checkStrictly: true,
  label: 'areaName',
  value: 'pkid',
}
const pkids = ref<string[]>([])

const handleAreaCodeChange = (item: any) => {
  const val = item as string[]
  if (val) {
    userForm.refId = val[val.length - 1]
  } else {
    userForm.refId = ''
  }
}

const areaList = ref<DivisionData[]>([])

const title = ref('新增用户')

const emit = defineEmits(['closeDialog', 'updateUser'])

const closeDialog = () => {
  emit('closeDialog')
}

const userForm = reactive<updateUserParams>({
  loginName: '',
  userName: '',
  loginPassword: '',
  confirmPassword: '',
  nickName: '',
  userPhone: '',
  roleId: '',
  refId: '',
  remark: '',
  userState: 1,
  pkid: '',
})

const userFormRef = ref()

const phoneNumberValidator = (
  rule: any,
  value: string,
  callback: ValidatorCallback
) => {
  if (!/^1[3456789]\d{9}$/.test(value)) {
    callback(new Error('请输入正确的手机号码'))
  } else {
    callback()
  }
}

const equalToPassword = (rule: any, value: any, callback: any) => {
  if (userForm.loginPassword !== value) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const findNodeById = (tree: any, targetId: any): any => {
  // console.log(tree, targetId)
  // 遍历树中的每个节点
  for (let i = 0; i < tree.length; i++) {
    // 检查当前节点的ID是否为目标ID
    if (tree[i].areaCode === targetId || tree[i].pkid === targetId) {
      // 如果是的话，返回当前节点
      return tree[i]
    }

    // 如果当前节点有子节点，则递归在子节点中查找
    if (tree[i].children && tree[i].children.length > 0) {
      const foundNode = findNodeById(tree[i].children, targetId)
      // 如果在子节点中找到了，则返回找到的节点
      if (foundNode !== undefined) {
        return foundNode
      }
    }
  }

  // 如果在树中没有找到目标ID，则返回undefined
  return undefined
}

const getLevelByRoleId = () => {
  let level = -1
  switch (userForm.roleId) {
    case 'citymanager':
      level = 0
      break
    case 'checkmanager':
      level = 1
      break
    case 'streetmanager':
      level = 2
      break
    case 'socialmanager':
      level = 3
      break
    case 'districtmanager':
      level = 5
      break
    default:
      {
        const f = props.userRoleDict.find(
          (item) => item.value === userForm.roleId
        )
        if (f) {
          level = f.level
          if (level === 1) {
            level = 2
          } else if (level === 2) {
            level = 1
          }
        }
      }
      break
  }
  return level
}

const deptValid = (rule: any, value: any, callback: any) => {
  const node = findNodeById(areaList.value, value)
  if (node) {
    const level = node.level
    const currentLevel = getLevelByRoleId()
    if (currentLevel === -1 && !value) {
      callback(new Error('请选择用户角色'))
    } else if (currentLevel === -1 && value) {
      callback()
    } else if (level !== currentLevel) {
      callback(new Error('用户角色与所属区域不匹配'))
    } else {
      callback()
    }
    // console.log(node)
    // callback()
  } else {
    callback(new Error('请选择用户所属区域'))
  }
}

const userRules = reactive({
  loginName: [
    {
      required: true,
      message: '登录名不能为空',
      trigger: 'blur',
    },
  ],
  userName: [
    {
      required: true,
      message: '真实姓名不能为空',
      trigger: 'blur',
    },
  ],
  // userPhone: [
  //   {
  //     required: true,
  //     message: '手机号码不能为空',
  //     trigger: 'blur',
  //   },
  //   {
  //     validator: phoneNumberValidator,
  //     trigger: 'blur',
  //   },
  // ],
  roleId: [
    {
      required: true,
      message: '请选择用户角色',
      trigger: 'change',
    },
  ],
  refId: [
    {
      required: true,
      message: '请选择用户所属区域',
      trigger: 'change',
    },
    {
      required: true,
      trigger: 'change',
      validator: deptValid,
    },
  ],
  loginPassword: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur',
    },
  ],
  confirmPassword: [
    { required: true, trigger: 'blur', message: '请再次输入您的密码' },
    { required: true, validator: equalToPassword, trigger: 'blur' },
  ],
})
const formatQuery = (sourceObject: any) => {
  const extractedObject = {}

  function extractAttributes(source: any, target: any) {
    for (const key in source) {
      const value = source[key]

      if (value !== null && value !== undefined) {
        if (typeof value === 'object' && !Array.isArray(value)) {
          target[key] = {}
          extractAttributes(value, target[key])
        } else {
          target[key] = value
        }
      }
    }
  }

  extractAttributes(sourceObject, extractedObject)

  return extractedObject as updateUserParams
}

const getDeptList = () => {
  queryDeptListOld({
    districtFlag: 'true',
  }).then((res) => {
    if (res.success) {
      if (res.data && res.data!.length) {
        areaList.value = res.data!
      }
    }
  })
}

onMounted(() => {
  getDeptList()
})
const onSubmit = () => {
  userFormRef.value?.validate((valid: boolean) => {
    // console.log(valid)
    if (valid) {
      if (userForm.pkid) {
        const params = formatQuery(userForm)
        // delete params.userPhone
        delete params.loginPassword
        updateUser(userForm.pkid, params).then((res) => {
          if (res.success) {
            Message.success('更新用户成功')
            emit('updateUser')
          } else {
            Message.error(res.message)
          }
        })
      } else {
        const params = formatQuery(userForm)
        params.loginPassword = Base64.encode(params.loginPassword!)
        // delete params.userPhone
        addUser(params).then((res) => {
          if (res.success) {
            Message.success('添加用户成功')
            emit('updateUser')
          } else {
            Message.error(res.message)
          }
        })
      }
    }
  })
  // console.log(666)
}

const extractIds = (
  treeArray: DivisionData[],
  nodeId: string
): string[] | null => {
  // Find the node with the given ID
  const findNode = (
    node: DivisionData,
    pkid: string,
    parents: string[] = []
  ): string[] | null => {
    if (node.pkid === pkid) {
      return parents.concat(node.pkid)
    }

    if (Array.isArray(node.children)) {
      for (const child of node.children) {
        const found = findNode(child, pkid, parents.concat(node.pkid))
        if (found) {
          return found
        }
      }
    }

    return null
  }

  // Start the search from the root of the tree
  for (const node of treeArray) {
    const result = findNode(node, nodeId)
    if (result) {
      return result
    }
  }

  // If the node is not found, return null or handle the error as desired
  return null
}

const handleDialogOpen = () => {
  // console.log(props.userRoleDict)
  userFormRef.value?.resetFields()
  if (props.userInfo) {
    Object.assign(userForm, props.userInfo)
    if (props.userInfo.pkid) {
      title.value = '编辑用户'
    } else {
      title.value = '新增用户'
    }
    if (!props.userInfo.userState) {
      userForm.userState = 1
      userForm.pkid = ''
      userForm.loginPassword = ''
      userForm.confirmPassword = ''
    }
    if (props.userInfo.refId) {
      pkids.value = extractIds(areaList.value, props.userInfo.refId) || []
    } else {
      pkids.value = []
    }
  }
}
</script>

<style lang="scss">
.add-user-dialog {
  //width: 762px;
  //height: 683px;
  //background: #ffffff;
  border-radius: 4px;

  .el-dialog__header {
    border-bottom: 1px solid #e5e5e5;

    .el-dialog__title {
      width: 64px;
      height: 16px;
      font-size: 16px;
      font-weight: bold;
      color: #27475f;
    }
  }

  .el-form {
    .el-form-item {
      min-height: 42px;
      margin-bottom: 21px;
      align-items: center;
    }

    .el-cascader {
      width: 100%;
    }

    .el-select {
      width: 100%;
    }
  }

  .dialog-footer {
    width: 100%;
    height: 100%;
    text-align: center;
  }
}
</style>
